//
//  NewDevice1ViewController.m
//  Demo
//
//  Created by liao Echo on 13-10-17.
//

#import "NewDevice1ViewController.h"

@implementation UIImage (UIImageCategory)

-(UIImage*)scaleToSize:(CGSize)size {
    NSLog(@"category scalesToSize");
    //确定需要保留的区域
    if (size.width>=self.size.width && size.height>=self.size.height) {
        return self;
    }
    
    CGRect rect;
    CGSize imageSize = self.size;
    
    
    
    BOOL fill=YES;
    if (fill) {
        if (imageSize.height > imageSize.width) {
            NSLog(@"if");
            imageSize.width = floor((imageSize.width/imageSize.height) * size.height);
            imageSize.height = size.height;
        } else {
            NSLog(@"else");
            imageSize.height = floor((imageSize.height/imageSize.width) * size.width);
            imageSize.width = size.width;
        }
        rect=CGRectMake(0 + floor(size.width/2 - imageSize.width/2),
                        0 + floor(size.height/2 - imageSize.height/2),
                        imageSize.width, imageSize.height);
    } else  {
        if (imageSize.height < imageSize.width) {
            imageSize.height = floor((imageSize.height/imageSize.width) * size.width);
            imageSize.width = size.width;
        } else {
            imageSize.width = floor((imageSize.width/imageSize.height) * size.height);
            imageSize.height = size.height;
        }
        rect=CGRectMake(0 + floor(rect.size.width/2 - imageSize.width/2),
                        0 + floor(rect.size.height/2 - imageSize.height/2),
                        imageSize.width, imageSize.height);
    }
    
    NSLog(@"rect:%@",NSStringFromCGRect(rect));
    //裁剪缩放
    CGRect drawRect=CGRectMake(0, 0, rect.size.width, rect.size.height);
    UIGraphicsBeginImageContext(drawRect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    //CGContextSaveGState(context);
    CGContextAddRect(context, drawRect);
    //CGContextClip(context);
    
    [self drawInRect:drawRect];
    //CGContextRestoreGState(context);
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	return newImage;
}
@end


@interface NewDevice1ViewController ()

@end

@implementation NewDevice1ViewController
@synthesize _image;
@synthesize delegate;
@synthesize strFilename;
@synthesize modify, type;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    self.title = STR(@"红外遥控");
    if ([Global curLanguageEn]) {
        self.title = @"WIFI Smart IR Controler";
    }
    [super viewDidLoad];
    
    UIImage *image = IMG(@"new_device_big_bg.png");
    bg = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth-image.size.width/2)/2, 10, image.size.width/2, image.size.height/2)];
    bg.image = image;
    preRect = bg.frame;
    NSLog(@"%f %f", preRect.origin.x, preRect.origin.y);
    bg.userInteractionEnabled = YES;
    [self.view addSubview:bg];
    
    GoodLabel *titleLabel = [GoodLabel labelWithFont:15 title:STR(@"添加新设备")];
    if ([Global curLanguageEn]) {
        titleLabel.text = @"Add New Device";
    }
    if (modify) {
        titleLabel.text = STR(@"修改设备信息");
        if ([Global curLanguageEn]) {
            titleLabel.text = @"Revise The Device Info";
        }
    }
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.frame = CGRectMake(0, 0, FW(bg), 30);
    [bg addSubview:titleLabel];
    
    for (int i=0; i<2; i++) {
        image = IMG(@"device_text_bg.png");
        UIImageView *textbg = [[UIImageView alloc] initWithFrame:CGRectMake(5, 38+i*150, bg.frame.size.width-8, image.size.height/2)];
        textbg.image = image;
        [bg addSubview:textbg];
        
        GoodLabel *nameLabel = [GoodLabel labelWithFont:12 title:@"系统模版"];
        if ([Global curLanguageEn]) {
            nameLabel.text = @"System Templates";
        }
        nameLabel.frame = CGRectMake(10, 0, textbg.frame.size.width, textbg.frame.size.height);
        [textbg addSubview:nameLabel];
        if (i==1) {
            nameLabel.text = @"修改设备信息";
            if ([Global curLanguageEn]) {
                nameLabel.text = @"Revise The Device Info";
            }
        }
        
        image = nil;
        if (i == 1) {
            image = IMG(@"device_logo_edit.png");
            logo = [[UIButton alloc] initWithFrame:CGRectMake((bg.frame.size.width-image.size.width/2)/2, textbg.frame.origin.y+textbg.frame.size.height+10, image.size.width/2, image.size.height/2)];
            [logo setBackgroundImage:image forState:UIControlStateNormal];
            [logo addTarget:self action:@selector(modifyPressed) forControlEvents:UIControlEventTouchUpInside];
            [bg addSubview:logo];
        }
    }
    int count = 10;
    NSMutableArray *sourceImages = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i <count ; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", i+1]];
        if (i == 0) {
            image = IMG(@"icon_AIR.png");
        }else if (i == 1) {
            image = IMG(@"icon_TV.png");
        }else if (i == 2) {
            image = IMG(@"icon_STB.png");
        }else if (i == 3) {
            image = IMG(@"icon_SOUND.png");
        }else if (i == 4) {
            image = IMG(@"icon_CUSTOM.png"); 
        }
//        else if (i == 5) {
//            image = IMG(@"icon_dish.png");//
//        }
        else if (i == 5) {
            image = IMG(@"icon_xiaomi.png");
        }else if (i == 6) {
            image = IMG(@"icon_appleTV.png");
        }else if (i == 7) {
            image = IMG(@"icon_template_rf_one_key.png");
        }else if (i == 8) {
            image = IMG(@"icon_template_rf_two_key.png");
        }else if (i == 9) {
            image = IMG(@"icon_template_rf_three_key.png");
        }
        [sourceImages addObject:image];
    }
    CoverFlowView *coverFlowView = [CoverFlowView coverFlowViewWithFrame:CGRectMake(30, 60, 220, 100) andImages:sourceImages sideImageCount:2 sideImageScale:0.35 middleImageScale:0.6];
    coverFlowView.delegate = self;
    [bg addSubview:coverFlowView];
    
    int pos = 0;
    if (modify) {
        coverFlowView.userInteractionEnabled = NO;
        if (type == DEVICE_AIR) {
            pos = 0;
        }else if (type == DEVICE_TV) {
            pos = 1;
        }else if (type == DEVICE_STB) {
            pos = 2;
        }else if (type == DEVICE_SOUND) {
            pos = 3;
        }else if (type == DEVICE_CUSTOM) {
            pos = 4;
        }else if (type == DEVICE_XIAOMI) {
            pos = 5;
        }else if (type == DEVICE_APPLETV) {
            pos = 6;
        }else if (type == DEVICE_SOCKET1) {
            pos = 7;
        }else if (type == DEVICE_SOCKET2) {
            pos = 8;
        }else if (type == DEVICE_SOCKET3) {
            pos = 9;
        }
        for (int j=0; j<pos; j++) {
            [coverFlowView moveOneStep:YES];
        }
    }
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, FY(hScrollview), FX(hScrollview), FH(hScrollview))];
    [bg addSubview:view];
    
    image = IMG(@"new_device_bg.png");
    UIImageView *bg1 = [[UIImageView alloc] initWithFrame:CGRectMake((bg.frame.size.width-image.size.width/2)/2, 300, image.size.width/2, image.size.height/2)];
    bg1.userInteractionEnabled = YES;
    bg1.image = image;
    [bg addSubview:bg1];
    
    GoodLabel *descLabel = [GoodLabel labelWithFont:14 title:@"名称："];
    if ([Global curLanguageEn]) {
        descLabel.text = @"Name：";
    }
    descLabel.textColor = [UIColor blackColor];
    descLabel.frame = CGRectMake(15, 0, kScreenWidth, bg1.frame.size.height);
    [bg1 addSubview:descLabel];
    
    tf = [[UITextField alloc] initWithFrame:CGRectMake(60, 2, 150, bg1.frame.size.height-4)];
    tf.returnKeyType = UIReturnKeyDone;
    tf.backgroundColor = [UIColor whiteColor];
    tf.clearButtonMode = UITextFieldViewModeWhileEditing;
    tf.font = [UIFont systemFontOfSize:14];
    [bg1 addSubview:tf];
    tf.delegate = self;
    
    [self didChooseIndex:pos];
    
    image = IMG(@"device_logo_line.png");
    UIImageView *bgLine = [[UIImageView alloc] initWithFrame:CGRectMake((bg.frame.size.width-image.size.width/2)/2, 300+50, image.size.width/2, image.size.height/2)];
    bgLine.image = image;
    [bg addSubview:bgLine];
    
    UIButton *saveBtn = [[UIButton alloc] initWithFrame:CGRectMake((bg.frame.size.width-197)/2, 300+50+6, 197, 24)];
    saveBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [saveBtn setTitle:STR(@"保存") forState:UIControlStateNormal];
    if ([Global curLanguageEn]) {
        [saveBtn setTitle:@"Save" forState:UIControlStateNormal];
    }
    [saveBtn setBackgroundImage:IMG(@"APP_link_btn.png") forState:UIControlStateNormal];
    [saveBtn addTarget:self action:@selector(saveBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [bg addSubview:saveBtn];
}
-(void)didChooseIndex:(NSInteger)index{
    selectIndex = index;
    if (selectIndex == 0) {
        tf.text = STR(@"空调");
    }else if (selectIndex == 1) {
        tf.text = STR(@"电视机");
    }else if (selectIndex == 2) {
        tf.text = STR(@"机顶盒");
    }else if (selectIndex == 3) {
        tf.text = STR(@"音响");
    }else if (selectIndex == 4) {
        tf.text = STR(@"自定义");
    }
    else if (selectIndex == 5) {
        tf.text = STR(@"小米盒子");
    }else if (selectIndex == 6){
        tf.text = STR(@"Apple TV");
    }else if (selectIndex == 7){
        tf.text = STR(@"触摸开关");
    }else if (selectIndex == 8){
        tf.text = STR(@"触摸开关");
    }else if (selectIndex == 9){
        tf.text = STR(@"触摸开关");
    }
    tf.text = [Global chinaToEn:tf.text];
    self._image = nil;
    [logo setBackgroundImage:IMG(@"device_logo_edit.png") forState:UIControlStateNormal];
}
-(void)modifyPressed{
    if ([Global curLanguageEn]) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"Choose Picture" delegate:self cancelButtonTitle:@"Cancel"destructiveButtonTitle:nil otherButtonTitles:@"Camera", @"Choose From Album", nil];
        [sheet showInView:self.view];
        
    }else{
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"图片选择" delegate:self cancelButtonTitle:STR(@"取消") destructiveButtonTitle:nil otherButtonTitles:STR(@"拍照"), STR(@"从手机相册选择"), nil];
        [sheet showInView:self.view];
    }
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    UIImagePickerController *imagepickerController = nil;
    if (buttonIndex == 0) {
        imagepickerController = [[UIImagePickerController alloc] init];
        imagepickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else if (buttonIndex == 1) {
        imagepickerController = [[UIImagePickerController alloc] init];
        imagepickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    if (imagepickerController) {
        imagepickerController.allowsEditing = NO;
        imagepickerController.delegate = self;
        [self presentViewController:imagepickerController animated:YES completion:^{
            
        }];
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];//
    self._image = [image scaleToSize:CGSizeMake(160, 160)];
    [logo setBackgroundImage:image forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:^{}];
}
-(void)saveBtnPressed:(UIButton*)btn{
    if ([tf.text length] > 0) {
        if (self._image) {
            NSData *uploadImageData = UIImageJPEGRepresentation(self._image, 0.6f);
            self.strFilename = [[IDGenerator share] genID];
            [uploadImageData writeToFile:[DataManager storePathWithFileName:self.strFilename] atomically:YES];
        }
        if (modify) {
            [delegate modifyNewDeviceDelegateName:[NSString stringWithFormat:@"%d",selectIndex] name:tf.text fileid:self.strFilename];
        }else{
            [delegate NewDeviceDelegateName:[NSString stringWithFormat:@"%d",selectIndex] name:tf.text fileid:self.strFilename];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma -
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    [UIView animateWithDuration:.3 animations:^{
        bg.center = CGPointMake(bg.center.x, bg.center.y-220);
    } completion:^(BOOL finished) {

    }];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [UIView animateWithDuration:.3 animations:^{
        bg.frame = preRect;
    } completion:^(BOOL finished) {
        
    }];
    [textField resignFirstResponder];
    return YES;
}

@end

























